package org.zxl.iotest.netty.protobuf.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.zxl.iotest.netty.protobuf.server.ServerMessageParse;
import org.zxl.iotest.netty.protobuf.util.ServerMessageID;
import org.zxl.iotest.netty.protobuf.util.ZxlMsg;

import java.util.Objects;

@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
       /* CommonResult commonResult = CommonResult.newBuilder()
                .setBSuccess(true)
                .setIntCodeId(8888)// 使用这个字段作为客户端id；偷懒，没有构造专门用于注册的protobuf类
                .setStrMsg("success")
                .build();
        *//*Integer msgId = 12301;
        byte[] msgIdBytes = ByteUtils.intToBytesBE(msgId);

        Integer msgLength = commonResult.toByteArray().length;
        byte[] msgLengthBytes = ByteUtils.intToBytesBE(msgLength);

        byte[] reqBytes = ByteUtils.concatenateByteArrays(msgIdBytes, msgLengthBytes, commonResult.toByteArray());

        ctx.channel().writeAndFlush(reqBytes);*//*

        ZxlMsgSendUtil.sendMsg(ctx.channel(), MessageID.REGISTER, commonResult);*/
        new TcpClientService().sendRegister(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.info("channelInactive***************");

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("ClientHandler, channelRead");
        ByteBuf buf = (ByteBuf) msg;
        ZxlMsg zxlMsg = ServerMessageParse.parse(buf);

        if(Objects.equals(zxlMsg.getMsgId() , ServerMessageID.ACTIVE_CHECK)){
            System.out.println("active check");
            new TcpClientService().sendHeartbeat(ctx.channel());
        }
    }
}
